﻿using System;
using UnityEngine.Networking;
using XLua;

public class HttpManager : Singleton<HttpManager>
{
    public static void Get(string url, LuaFunction onSuccess, LuaFunction onFailure, int timeout = 10)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
        unityWebRequest.timeout = timeout;
        var asyncOperation = unityWebRequest.SendWebRequest();
        asyncOperation.completed += (obj) =>
        {
            bool isError = asyncOperation.webRequest.result == UnityWebRequest.Result.ConnectionError || asyncOperation.webRequest.result == UnityWebRequest.Result.ProtocolError;
            if (isError)
            {
                if (onFailure != null)
                {
                    onFailure.Call(asyncOperation.webRequest.error);
                }
            }
            else
            {
                if (onSuccess != null)
                {
                    onSuccess.Call(asyncOperation.webRequest.downloadHandler.text);
                }
            }
            asyncOperation.webRequest.Abort();
            unityWebRequest.Dispose();
        };
    }

    public static void PostJson(string url, string json, LuaFunction onSuccess, LuaFunction onFailure)
    {
        UnityWebRequest unityWebRequest = new UnityWebRequest(url, "POST");
        unityWebRequest.useHttpContinue = false; //需要设置该值为false，否则数据会出现不完整导致失败
        unityWebRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json));
        unityWebRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        unityWebRequest.downloadHandler = new DownloadHandlerBuffer();
        unityWebRequest.timeout = 20;
        var asyncOperation = unityWebRequest.SendWebRequest();
        asyncOperation.completed += (obj) =>
        {
            bool isError = asyncOperation.webRequest.result == UnityWebRequest.Result.ConnectionError || asyncOperation.webRequest.result == UnityWebRequest.Result.ProtocolError;
            if (isError)
            {
                if (onFailure != null)
                {
                    //onFailure(asyncOperation.webRequest.error);
                    onFailure.Call(string.Format("responseCode:{0} errorMsg:{1}", asyncOperation.webRequest.responseCode, asyncOperation.webRequest.error));
                }
            }
            else
            {
                if (onSuccess != null)
                {
                    onSuccess.Call(asyncOperation.webRequest.downloadHandler.text);
                }
            }
            asyncOperation.webRequest.Abort();
            unityWebRequest.Dispose();
        };
    }

}
